package com.ufcg.lvc.server;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * 
 * Servlet para fazer o upload de arquivos para o servidor.
 * 
 * @author Larissa
 *
 */
public class FileUploadServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ServletFileUpload upload = new ServletFileUpload();

		try {
			FileItemIterator iter = upload.getItemIterator(request);

			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				String nome = item.getName();
				RandomString r = new RandomString(20);
				String newName = r.nextString() + "1"
						+ nome.substring(nome.length() - 4);
				if (item.isFormField()) {
					// if(item.getFieldName().compareTo("userID")==0){
					// userId = Streams.asString(item.openStream());
					// }
					// else if(item.getFieldName().compareTo("attempts")==0){
					// attempts = Streams.asString(item.openStream());
					// }
				} else {
					String name = item.getFieldName();
					String fileName = "";

					if (name.compareTo("fileUpload") == 0) {
						InputStream stream = item.openStream();
						
						// fileName = "C:/Users/Larissa Costa/workspace-Android/Teste_/Teste_/war/"+newName;
						fileName = "C:/Users/Larissa/workspace/Teste_/war/"	+ newName;
						OutputStream output = new FileOutputStream(fileName);
						String fileName2 = "C:/ServerArea/img/" + newName;
						OutputStream output2 = new FileOutputStream(fileName2);

						// Process the input stream
						ByteArrayOutputStream out = new ByteArrayOutputStream();
						out.writeTo(output);
						ByteArrayOutputStream out2 = new ByteArrayOutputStream();
						out2.writeTo(output2);

						int len;
						byte[] buffer = new byte[8192];
						while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
							out.write(buffer, 0, len);
							output.write(buffer, 0, len);

							out2.write(buffer, 0, len);
							output2.write(buffer, 0, len);
						}

						int maxFileSize = 10 * (1024 * 1024); // 10 megs max
						if (out.size() > maxFileSize) {
							throw new RuntimeException("File is > than " + maxFileSize);
						}
						output.close();
						output2.close();
					}
					response.getWriter().print(fileName);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public class RandomString {

		private final char[] symbols = new char[36];
		private final Random random = new Random();
		private final char[] buf;

		public RandomString(int length) {
			if (length < 1)
				throw new IllegalArgumentException("length < 1: " + length);
			buf = new char[length];
			for (int idx = 0; idx < 10; ++idx)
				symbols[idx] = (char) ('0' + idx);
			for (int idx = 10; idx < 36; ++idx)
				symbols[idx] = (char) ('a' + idx - 10);
		}

		public String nextString() {
			for (int idx = 0; idx < buf.length; ++idx)
				buf[idx] = symbols[random.nextInt(symbols.length)];
			return new String(buf);
		}
	}
}
